package fr.enssat.tpcloud.dao;

import java.util.Collection;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import fr.enssat.tpcloud.model.Post;
import fr.enssat.tpcloud.model.User;

/**
 * 
 * Hibernate DAO for Post.
 *
 */
public class PostDao extends HibernateDaoSupport {

    /**
     * Get all post.
     * 
     * @return collection of post
     */
    @SuppressWarnings("unchecked")
    public Collection<Post> getAllPost() {
        return getHibernateTemplate().loadAll(Post.class);
    }

    /**
     * Save a new post.
     * 
     * @param post post to save
     */
    public void save(Post post) {
           getHibernateTemplate().save(post);
    }

    /**
     * Delete a post.
     * 
     * @param post post to delete
     */
    public void delete(Post post) {
       getHibernateTemplate().delete(post);
    }
    
    @SuppressWarnings("unchecked")
    public List<Post> findReportPost(String email) {
        
    	// Critere pour trouver le user
        DetachedCriteria criteria = DetachedCriteria.forClass(User.class)
            .add(Restrictions.gt("nbReport", 0));
        
        List<Post> allResult = getHibernateTemplate().findByCriteria(criteria);

        return allResult;
    }

    @SuppressWarnings("unchecked")
	public Post findPostById(int id) {
		
		Post post = null;
		
		DetachedCriteria criteria = DetachedCriteria.forClass(Post.class)
	            .add(Restrictions.eq("id", id));
		
		System.out.println("PostDao::findPostById : requete effectuee !");
		
		List<Post> allResult = getHibernateTemplate().findByCriteria(criteria);
		
		System.out.println("PostDao::findPostById : recuperation des resultats ok !");
		
		if(allResult.size() == 1)
			post = allResult.get(0);
		
		System.out.println("PostDao::findPostById : taille du résultat = " + allResult.size());
		
		return post;
	}

}
